package com.mxl.service.notify.http;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.mxl.dao.cashorder.model.GatewayReturnLog;
import com.mxl.service.cashorder.impl.GatewayDispatchServiceImpl;

/**
 * 商户通知
 * 
 * @author xianglin.mo
 * 
 */
@Service("httpSender")
public class DefaultHttpSenderImpl implements HttpSender {
	private static final Logger logger = LoggerFactory
			.getLogger(GatewayDispatchServiceImpl.class);
	private HttpClient httpClient;

	public DefaultHttpSenderImpl() {
		MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
		httpClient = new HttpClient(manager);
		httpClient.getHttpConnectionManager().getParams()
				.setConnectionTimeout(8000);
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(10000);
	}

	public GatewayReturnLog postHttpData(String url) {
		GatewayReturnLog response = new GatewayReturnLog();
		response.setCreationDate(new Date());
		response.setSubmitAddr(url);

		HttpMethod method = null;
		InputStream is = null;
		int statusCode = 0;
		// 判断url是否合法，以http，或者https开头
		logger.info("********notify member url:{}", url);
//		if (!url.startsWith("http://") || !url.startsWith("https://")) {
//			logger.info("notify member Http Get url:" + url);
//			url = "http://" + url;
//		}
		// 去掉url中的空格
		url.replaceAll(" ", "%20");
		try {
			method = new GetMethod(url);
			statusCode = httpClient.executeMethod(method);
			String context = method.getResponseBodyAsString();
			context = context != null && context.length() > 2000 ? context
					.substring(0, 2000) : context;
			response.setResponseContent(context);
			// 被电信截获页面
			// if (responseContent.indexOf("114search") != -1) {
			// throw new HttpException("Oops, It is catched by 114");
			// }

			// 商户重定向页面, 仅判断做一次重定向
			if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
					|| (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
					|| (statusCode == HttpStatus.SC_SEE_OTHER)
					|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
				Header header = method.getResponseHeader("location");
				if (header != null) {
					String newuri = header.getValue();
					if ((newuri == null) || (newuri.equals(""))) {
						newuri = "/";
					}
					logger.info("notify member two Http Get redirect url:"
							+ newuri);
					GetMethod redirect = new GetMethod(newuri);
					statusCode = httpClient.executeMethod(redirect);

					response.setResponseContent(redirect
							.getResponseBodyAsString(2000));
				} else {
					logger.info("notify member two invalid redirect. url = "
							+ url);
				}
			}
			response.setStatusCode(statusCode);
			// 当获得返回状态为200时， 认为商户返回成功交易
		} catch (Exception e) {
			logger.error("notify member fail........", e);
			response.setStatusCode(statusCode);
			response.setResponseContent(e.getMessage());
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (method != null) {
					method.releaseConnection();
				}
			} catch (IOException ie) {
				logger.error("close io fail........", ie);
			}
		}
		response.setLastupDate(new Date());
		return response;
	}
}
